export const useTagsBarStore = defineStore({
  id: 'tagsBar',
  state: () => ({
    tabActive: '',
    visitedRoutes: [],
  }),
  actions: {
    setTabActive(path) {
      this.tabActive = path
    },
    addTabs(tag) {
      if (tag.name && tag.meta?.tagHidden !== true) {
        let matched = [tag.name]
        if (tag.matched) {
          matched = tag.matched.map(item => item.name)
        }
        this.addVisitedRoute({
          ...tag,
          matched,
          loaded: true,
        })
        this.setTabActive(tag.fullPath)
      }
    },
    addVisitedRoute(route) {
      let target = this.visitedRoutes.find(item => item.path === route.path)
      if (target) {
        if (route.fullPath !== target.fullPath) {
          Object.assign(target, route)
        }
        return
      }
      this.visitedRoutes.push(Object.assign({}, route))
    },
    delVisitedRoute(route) {
      this.visitedRoutes.forEach((item, index) => {
        if (item.path === route.path) {
          this.visitedRoutes.splice(index, 1)
        }
      })
    },
    delOthersVisitedRoutes(route) {
      this.visitedRoutes = this.visitedRoutes.filter(item => item.meta.affix || item.path === route.path)
    },
    delLeftVisitedRoutes(route) {
      let index = this.visitedRoutes.length
      this.visitedRoutes = this.visitedRoutes.filter(item => {
        if (item.name === route.name) {
          index = this.visitedRoutes.indexOf(item)
        }
        return item.meta.affix || index <= this.visitedRoutes.indexOf(item)
      })
    },
    delRightVisitedRoutes(route) {
      let index = this.visitedRoutes.length
      this.visitedRoutes = this.visitedRoutes.filter(item => {
        if (item.name === route.name) {
          index = this.visitedRoutes.indexOf(item)
        }
        return item.meta.affix || index >= this.visitedRoutes.indexOf(item)
      })
    },
    delAllVisitedRoutes() {
      this.visitedRoutes = this.visitedRoutes.filter(item => item.meta.affix)
    },
    resetTagBar() {
      this.tabActive = ''
      this.visitedRoutes = []
    },
  },
})
